#include "SList.h"

ListNode* BuyListNode(SListDataType x) {
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	node->prev = NULL;
	node->next = NULL;
	node->data = x;
	return node;
}

void ListPrint(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

ListNode* ListInit() {
	ListNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListPushBack(ListNode* phead, SListDataType x) {
	assert(phead);

	//ListNode* tail = phead->prev;
	/*ListNode* newnode = BuyListNode(x);

	tail->next = newnode;
	newnode->prev = tail;

	newnode->next = phead;
	phead->prev = newnode;*/

	ListInsert(phead->prev, x);
}

void ListPopBack(ListNode* phead) {
	/*assert(phead);
	assert(phead->next != phead);

	ListNode* tail = phead->prev;
	ListNode* tailPrev = tail->prev;
	phead->prev = tailPrev;
	tailPrev->next = phead;
	free(tail);
	tail = NULL;*/

	ListErase(phead->prev);
}

void ListPushFront(ListNode* phead, SListDataType x) {
	assert(phead);
	//ListNode* first = phead->next;
	/*ListNode* newnode = BuyListNode(x);

	phead->next = newnode;
	newnode->next = first;

	first->prev = newnode;
	newnode->prev = phead;*/
	ListInsert(phead->next, x);

}

void ListPopFront(ListNode* phead) {
	/*assert(phead);
	assert(phead->next != phead);

	ListNode* first = phead->next;
	ListNode* second = first->next;

	phead->next = second;
	first->prev = phead;

	free(first);
	first = NULL;*/

	ListErase(phead->next);
}

ListNode* ListFind(ListNode* phead, SListDataType x) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, SListDataType x) {
	assert(pos);

	ListNode* posPrev = pos->prev;
	ListNode* newnode = BuyListNode(x);

	pos->prev = newnode;
	newnode->next = pos;

	newnode->prev = posPrev;
	posPrev->next = newnode;
}

void ListErase(ListNode* pos) {
	assert(pos);
	ListNode* posPrev = pos->prev;
	ListNode* posNext = pos->next;

	posPrev->next = posNext;
	posNext->prev = posPrev;

	free(pos);
	pos = NULL;

}

void ListDestroy(ListNode* phead) {
	//assert(phead);

	//ListNode* cur = phead;
	//while (cur != phead) {
	//	ListNode* next = cur->next;
	//	free(cur);
	//	cur = next;
	//}

	ListClear(phead);
	free(phead);
}

void ListClear(ListNode* phead) {
	assert(phead);

	ListNode* cur = phead->next;
	while (cur != phead) {
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	phead->next = phead;
	phead->prev = phead;
}